const User = require('../models/user')
const CryptoJS = require('crypto-js')
const router = require('express').Router()
const Token = require('../utils/token')

router.post('/', (req, res) => {
  const {username, password} = req.body
  // 查询用户
  User
    .find({username})
    .then(data => {
      if (data.length === 1) {
        const [user] = data
        if (CryptoJS.MD5(password).toString() === user.password) {
          // 待保存到 token 中的数据
          const payload = {
            username,
            name: user.name
          }
          // 生成 token
          const token = Token.generateToken(payload)

          // 用户名与密码正确，验证通过
          res.json({
            code: 200,
            data: {
              message: '登录成功',
              token
            }
          })
          return
        }
      }
      res.json({
        code: 200,
        data: {
          message: '用户名或密码错误'
        }
      })
    })
})

module.exports = router
